package com.sinping.qh.utils.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
/**
 * Created by songzhitao on 2019/4/23.
 */
//证明是一个配置文件(使用@Component也可以,因为点入后会发现@Configuration还是使用了@Component)
//@Configuration
//证明是一个切面
//@Aspect
public class ControllerAOP {

    private static final Logger logger = LoggerFactory.getLogger(ControllerAOP.class);
    public final String string = "execution(*  *..*.*.controller..*.*(..))";
    private static final String UTF_8 = "utf-8";

    //环绕aop
    //execution表达式 此表达式表示扫描controller下所有类的所有方法都执行此aop
//    @Around("execution (* com.sinping.qh.api..*.*.*(..))")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        Object result = pjp.proceed();
        try {
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes sra = (ServletRequestAttributes) ra;
            HttpServletRequest request = sra.getRequest();
            long startTime = System.currentTimeMillis();
//        String url = request.getRequestURL().toString();
            String method = request.getMethod();
            String uri = request.getRequestURI();
            String queryString = request.getQueryString();
            Object[] args = pjp.getArgs();
            String params = "";
            // result的值就是被拦截方法的返回值
            //获取请求参数集合并进行遍历拼接
            if (args.length > 0) {
                if ("POST".equals(method)) {
                    Object object = args[0];
                    params = JSON.toJSONString(object, SerializerFeature.WriteMapNullValue);
                } else if ("GET".equals(method)) {
                    params = queryString;
                }
                params = URLDecoder.decode(params,UTF_8);
            }
            long endTime = System.currentTimeMillis();
            logger.info("--------------------controller aop: requestMethod:{}, url:{}, params:{}, responseBody:{}, elapsed:{}ms.", method , uri,  params,
                    JSON.toJSONString(result,SerializerFeature.WriteMapNullValue),(endTime - startTime));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("log error !!",e);
        }
        return result;
    }
}